package cn.iocoder.yudao.module.call.controller.admin.group;

import cn.hutool.core.collection.ListUtil;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.module.call.dal.dataobject.cmskill.CmServiceSkillDO;
import cn.iocoder.yudao.module.call.enums.CallClientEnum;
import cn.iocoder.yudao.module.call.enums.CallDistributionEnum;
import cn.iocoder.yudao.module.call.service.cmserviceskill.CmServiceSkillService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;

import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.call.controller.admin.group.vo.*;
import cn.iocoder.yudao.module.call.dal.dataobject.group.GroupDO;
import cn.iocoder.yudao.module.call.service.group.GroupService;

@Tag(name = "呼叫中心 - 班组")
@RestController
@RequestMapping("/call/group")
@Validated
public class GroupController {

    @Resource
    private GroupService groupService;

    @Resource
    private CmServiceSkillService cmServiceSkillService;

    @Resource
    private AdminUserApi adminUserApi;

    @PostMapping("/create")
    @Operation(summary = "创建班组")
    @PreAuthorize("@ss.hasPermission('call:group:create')")
    public CommonResult<Long> createGroup(@Valid @RequestBody GroupSaveReqVO createReqVO) {
        return success(groupService.createGroup(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新班组")
    @PreAuthorize("@ss.hasPermission('call:group:update')")
    public CommonResult<Boolean> updateGroup(@Valid @RequestBody GroupSaveReqVO updateReqVO) {
        groupService.updateGroup(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除班组")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('call:group:delete')")
    public CommonResult<Boolean> deleteGroup(@RequestParam("id") Long id) {
        groupService.deleteGroup(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得班组")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('call:group:query')")
    public CommonResult<GroupRespVO> getGroup(@RequestParam("id") Long id) {
        GroupDO group = groupService.getGroup(id);
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(ListUtil.of(group.getOwnerUserId()));
        return success(BeanUtils.toBean(group, GroupRespVO.class, item -> {
            buildRespVO(item, userMap);
        }));
    }

    @GetMapping("/page")
    @Operation(summary = "获得班组分页")
    @PreAuthorize("@ss.hasPermission('call:group:query')")
    public CommonResult<PageResult<GroupRespVO>> getGroupPage(@Valid GroupPageReqVO pageReqVO) {
        PageResult<GroupDO> pageResult = groupService.getGroupPage(pageReqVO);
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(convertSet(pageResult.getList(), GroupDO::getOwnerUserId));
        return success(BeanUtils.toBean(pageResult, GroupRespVO.class, group -> {
            buildRespVO(group, userMap);
        }));
    }

    @GetMapping("/simple-list")
    @Operation(summary = "获得班组列表")
    @PreAuthorize("@ss.hasPermission('call:group:query')")
    public CommonResult<List<GroupRespVO>> getGroupSimpleList() {
        GroupPageReqVO pageReqVO = new GroupPageReqVO();
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<GroupDO> result = groupService.getGroupPage(pageReqVO).getList();
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(convertSet(result, GroupDO::getOwnerUserId));
        return success(BeanUtils.toBean(result, GroupRespVO.class, group -> {
            buildRespVO(group, userMap);
        }));
    }

    @GetMapping("/skill-list")
    @Operation(summary = "获得班组/技能组")
    @PreAuthorize("@ss.hasPermission('call:group:query')")
    public CommonResult<List<GroupRespVO>> getSkillList() {
        GroupPageReqVO pageReqVO = new GroupPageReqVO();
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<GroupDO> result = groupService.getGroupPage(pageReqVO).getList();
        Collection<Long> ids = result.stream().map(GroupDO::getThirdPartyId).map(Long::parseLong).collect(Collectors.toSet());
        Map<Long, CmServiceSkillDO> skillMap = cmServiceSkillService.getMap(ids);
        return success(BeanUtils.toBean(result, GroupRespVO.class, group -> {
            MapUtils.findAndThen(skillMap, Long.parseLong(group.getThirdPartyId()), skill -> {
                group.setSkillId(skill.getSkillId());
            });
        }));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出班组 Excel")
    @PreAuthorize("@ss.hasPermission('call:group:export')")
    @OperateLog(type = EXPORT)
    public void exportGroupExcel(@Valid GroupPageReqVO pageReqVO,
                                 HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<GroupDO> list = groupService.getGroupPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "班组.xls", "数据", GroupRespVO.class,
                BeanUtils.toBean(list, GroupRespVO.class));
    }

    public void buildRespVO(GroupRespVO group, Map<Long, AdminUserRespDTO> userMap) {
        CallDistributionEnum callDistributionEnum = CallDistributionEnum.getByCode(group.getCallDistribution());
        group.setCallDistributionName(callDistributionEnum.getName());

        MapUtils.findAndThen(userMap, group.getOwnerUserId(), user -> {
            group.setOwnerUser(user.getNickname());
        });
    }

}